package com.xr.common.utils.file;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.xr.common.config.XRConfig;
import com.xr.common.constant.Constants;
import com.xr.common.exception.file.FileNameLengthLimitExceededException;
import com.xr.common.exception.file.FileSizeLimitExceededException;
import com.xr.common.exception.file.InvalidExtensionException;
import com.xr.common.utils.DateUtils;
import com.xr.common.utils.StringUtils;
import com.xr.common.utils.uuid.Seq;
/**
 * description: 云托管文件上传
 *
 * @author: wls
 * @date: 2023/11/6 13:52
 * @version:1.0
 */
@Component
public class FileUploadUtilsCloud{


    private static RestTemplate restTemplate;

    @Autowired
    public FileUploadUtilsCloud(RestTemplate restTemplate){
        FileUploadUtilsCloud.restTemplate = restTemplate;
    }

    private static String prod;

    @Value("${wxcloudprod.prod}")
    public void setProd(String prod){
        FileUploadUtilsCloud.prod = prod;
    }

    private static final String uploadFileUrl = "https://api.weixin.qq.com/tcb/uploadfile";

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 200;

    /**
     * 默认上传的地址
     */
    private static String defaultBaseDir = XRConfig.getProfile();

    public static void setDefaultBaseDir(String defaultBaseDir)
    {
        FileUploadUtilsCloud.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir()
    {
        return defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param fileName 上传的文件名称
     * @return 文件名称
     * @throws Exception
     */
    public static final JSONObject upload(String fileName) throws IOException
    {
        try
        {
            return upload(getDefaultBaseDir(), fileName, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param fileName 上传的文件名称
     * @return 文件名称
     * @throws IOException
     */
    public static final JSONObject upload(String baseDir, String fileName) throws IOException
    {
        try
        {
            return upload(baseDir, fileName, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 云托管文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param fileName 上传的文件名称
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException 比如读写文件出错时
     * @throws InvalidExtensionException 文件校验异常
     */
    public static final JSONObject upload(String baseDir, String fileName, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException
    {
        Logger logger = LoggerFactory.getLogger(FileUploadUtilsCloud.class);
        int fileNameLength = fileName.length();
        if (fileNameLength > FileUploadUtilsCloud.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtilsCloud.DEFAULT_FILE_NAME_LENGTH);
        }

        String name = extractFilename(fileName);

        //云托管上传
        String[] paths = baseDir.split("/");
        String newFileName = "uploadPath/" + paths[paths.length - 1] + "/" + name;//云托管文件名（路径+文件名）

        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("env", prod);
        requestMap.put("path", newFileName);
        logger.debug(requestMap.toString());
        String preUploadRes = restTemplate.postForObject(uploadFileUrl,requestMap, String.class);
        logger.debug(preUploadRes);
        JSONObject preUploadResObj = JSONObject.parseObject(preUploadRes);

        assert preUploadResObj != null;
        if(preUploadResObj.get("errcode").equals(0)) {
            logger.debug("获取上传链接成功");
            preUploadResObj.put("key", newFileName);
            return preUploadResObj;
        }else{
            throw new ArithmeticException(preUploadResObj.getString("errmsg"));
        }
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(String fileName)
    {
        return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                fileName, Seq.getId(Seq.uploadSeqType), getExtension(fileName));
    }


    /**
     * 获取文件名的后缀
     *
     * @param fileName 表单文件名
     * @return 后缀名
     */
    public static final String getExtension(String fileName)
    {
        return FilenameUtils.getExtension(fileName);
    }
}
